#-*-coding:utf-8-*-
# Create your views here.
from django.shortcuts import * 
from django.contrib.auth.models import User
from django.contrib.auth import *
from django.contrib.auth.decorators import *
from django.template import *
from pinkewang.member.forms import *
from pinkewang.member.models import *


def register(request):
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password'])
            user.save()
            member = Member(user = user)
            member.save()
            return HttpResponseRedirect('/thanks/')
    else:
        form = RegisterForm()
    return render_to_response('member/register.html', {'form':form})

def home_page(request):
    members = Member.objects.all()[:10]
    return render_to_response('home_page.html', {'members':members},  context_instance=RequestContext(request))
    
def user_login(request):
    if request.POST:
        form = LoginForm(request.POST)
        if form.is_valid():
            user = authenticate(username = form.cleaned_data['username'], password = form.cleaned_data['password'])
            if user is not None:
                login(request, user)
                return redirect("/")
    else:
        form = LoginForm()
    return render_to_response('member/login.html', {'form': form})

def user_logout(request):
    logout(request)
    return redirect("/")

def profile(request, id):
    user_info = User.objects.get(id = id)
    member = Member.objects.get(user = user_info.id)
    return render_to_response('member/profile.html', {'user_info': user_info, 'member': member}, context_instance=RequestContext(request))

@login_required
def manage(request):
    member = Member.objects.get(user = request.user.id)
    if request.POST:
        form = ProfileForm(request.POST, instance = member)
        if form.is_valid():
            form.save()
            return redirect("/manage/")
    else:
        form = ProfileForm(instance = member)
    return render_to_response('member/manage.html', {'form': form}, context_instance=RequestContext(request))
